<template>
  <up-upload
      :fileList="fileList"
      @afterRead="afterRead"
      @delete="deletePic"
      :multiple="multiple"
      :maxCount="maxCount"
      :maxSize="maxSize"
      @oversize="oversize"
  >
      <view class="default-slot">
        <slot>
          <up-icon name="camera-fill" color="rgb(211, 212, 214)" size="32rpx"></up-icon>
        </slot>
      </view>
  </up-upload>
</template>

<script>
import config from "@/config";
import {getToken} from "@/utils/auth";
import {listByIds} from "@/api/system/oss";

export default {
  props: {
    modelValue: [String, Object, Array],
    multiple: {
      type: Boolean,
      default: false
    },
    maxCount: {
      type: Number,
      default: 1
    },
  },
  data() {
    return {
      fileList: [],
      uploadUrl: config.baseUrl + "/system/oss/upload",
      fileMaxSize: 1024 * 1024, // 超出1M开启压缩
      maxSize: 20 * 1024 * 1024, //图片最大不能超过20M
    }
  },
  watch: {
     modelValue: {
       async handler(val) {
         if (val) {
           // 首先将值转为数组
           let list;
           if (Array.isArray(val)) {
             list = val;
           } else {
             await listByIds(val).then(res => {
               list = res.data;
             })
           }
           // 然后将数组转为对象数组
           this.fileList = list.map(item => {
             // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
             if (typeof item === "string") {
               item = {name: item, url: item};
             } else {
               // 此处name使用ossId 防止删除出现重名
               item = {name: item.ossId, url: item.url, ossId: item.ossId};
             }
             return item;
           });
         } else {
           this.fileList = [];
           return [];
         }
       },
       deep: true,
       immediate: true
    },
  },
  methods: {
    oversize() {
      this.$modal.msg({
        title: "图片最大不能超过20M",
        icon: 'none'
      })
    },
    deletePic(event) {
      this.fileList.splice(event.index, 1)
      this.$emit("update:modelValue", this.fileList.map(item => item.ossId).join(','));
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file)
      let fileListLen = this.fileList.length
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        const {url, ossId} = await this.uploadFilePromise(lists[i].url)
        let item = this.fileList[fileListLen]
        this.fileList.splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url,
          ossId
        }))
        fileListLen++
      }
      this.$emit("update:modelValue", this.fileList.map(item => item.ossId).join(','));
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.uploadUrl,
          filePath: url,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + getToken()
          },
          success: (res) => {
            resolve(JSON.parse(res.data).data)
          }
        });
      })
    }
  }
}

</script>

<style scoped lang="scss">
.default-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background-color: #f4f5f7;
  border-radius: 2px;
  margin: 0 8px 8px 0;
  box-sizing: border-box;
}
</style>
